#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/10/7 0:09
# @Author  : leon yan
# @Site    :
# @File    : applets.py
# @Software: PyCharm
import datetime

import serial
import serial.tools.list_ports
import struct


def rdCurrentTime():
    CurrentTime = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
    return CurrentTime


def To_hex_str(num):
    chaDic = {10: 'a', 11: 'b', 12: 'c', 13: 'd', 14: 'e', 15: 'f'}
    hexStr = ""
    if num < 0:
        num = num + 2 ** 32
    while num >= 16:
        digit = num % 16
        hexStr = chaDic.get(digit, str(digit)) + hexStr
        num //= 16
    hexStr = chaDic.get(num, str(num)) + hexStr
    return hexStr


def get_serial():
    plist = list(serial.tools.list_ports.comports())
    if len(plist) <= 0:
        print("The Serial port can't find!")
        return None
    else:
        aa = []
        for i in range(len(plist)):
            plist_0 = list(plist[i])
            serialName = plist_0[0]
            aa.append(serialName)
            # serialFd = serial.Serial(serialName, 9600, timeout=60)
            # print("check which port was really used >", serialFd.name)
        return aa


def get_baudrate():
    return [4800, 9600, 19200, 38400, 115200]


'''无符号==》有符号单字'''


def u2s(sData):
    if sData > 32767:
        return sData - 65536
    else:
        return sData


'''10进制2进制,返回的是一个list'''


def int2bin(svalue):
    aa = svalue
    aa2 = bin(aa)
    aa3 = list(aa2)
    bb = []
    for i in range(2, len(aa2)):
        if aa3[i] == "0":
            bb.append(0)
        else:
            bb.append(1)
    while len(bb) < 16:
        bb = [0] + bb
    bb.reverse()
    return bb


'''2进制10进制(这个2进制是没有前缀"0b"的)，不得超过16个bit,而且是一个list'''


def bin2int(svalue):
    svalue.reverse()
    svalue2 = []
    for i in range(len(svalue)):
        if svalue[i]:
            svalue2.append("1")
        else:
            svalue2.append("0")
    while len(svalue2) < 16:
        svalue2 = ["0"] + svalue2
    aa = ""
    for i in range(16):
        aa = aa + svalue2[i]
    aa = "0b" + aa
    return int(aa, 2)


'''更新某一字的指定位'''


def word2updateBit(sValue, num, xBool):
    aa = int2bin(sValue)
    aa[num] = xBool
    aa2 = bin2int(aa)
    return aa2


'''2个单字合并为一个双字整数'''


def SWd2DWd(L_int, H_int):
    aa1 = str((hex(L_int)))
    aa2 = str((hex(H_int)))
    aa3 = aa2[2:] + aa1[2:]
    val = int(aa3, 16)
    ''''''
    if -2 ** 31 <= val <= 2 ** 31 - 1:
        return val
    bin_string = bin(val & 0b11111111111111111111111111111111)
    int_val = int(bin_string, 2)
    if int_val > 2147483647:
        return -(~(int_val - 1) % 2 ** 32)
    return int_val


'''
32位整数范围
-2147483648 ~2147483647
32位拆分成2个单字
'''


def DWd2SWd(DWVal):
    if -2147483648 <= DWVal <= 2147483647:
        if 65535 >= DWVal >= 0:
            return 0, DWVal, hex(0), hex(DWVal)
        else:
            if DWVal > 65535 or DWVal < 0:
                if DWVal > 65535:
                    aa = str(hex(DWVal))
                    # print(aa)
                if DWVal < 0:
                    aa = str(hex(4294967296 + DWVal))
                lowWord = aa[-4:]
                HighWord = aa[0:-4]
                intlowWord = int(lowWord, 16)
                intHighWord = int(HighWord, 16)
                return intlowWord, intHighWord, hex(intlowWord), hex(intHighWord)
    else:
        return None

    '''限制在32位'''


def int32(val):
    if -2 ** 31 <= val <= 2 ** 31 - 1:
        return val
    bin_string = bin(val & 0b11111111111111111111111111111111)
    int_val = int(bin_string, 2)
    if int_val > 2147483647:
        return -(~(int_val - 1) % 2 ** 32)
    return int_val


'''no use'''


def str_2_bin(cls, theStr):
    """
    字符串转换为二进制
    """
    return ' '.join([bin(ord(c)).replace('0b', '') for c in theStr])


def bin_2_str(cls, theBin):
    """
    二进制转换为字符串
    """
    return ''.join([chr(i) for i in [int(b, 2) for b in theBin.split(' ')]])


def hex_2_f(theStr1, theStr2):
    aa1 = theStr1.replace('0x', '')
    if len(aa1) == 1:
        aa1 = "000" + aa1
    elif len(aa1) == 2:
        aa1 = "00" + aa1
    elif len(aa1) == 3:
        aa1 = "0" + aa1
    aa2 = theStr2.replace('0x', '')
    if len(aa2) == 1:
        aa2 = "000" + aa2
    elif len(aa2) == 2:
        aa2 = "00" + aa2
    elif len(aa2) == 3:
        aa2 = "0" + aa2
    cc = struct.unpack('>f', bytes.fromhex(aa2+aa1))[0]
    return cc


def float_to_hex(f):
    return hex(struct.unpack('<I', struct.pack('<f', f))[0])


def hex_to_int(h):
    return int(('0x' + h), 16)


'''32位16进制拆分2个字'''


def dHex_2_dd(dh):
    aa = dh.replace('0x', '')
    if aa == '0':
        return '0', '0'
    else:
        return aa[4:8], aa[0:4]


def second2time(eSecond):
    aa1 = divmod(eSecond, 3600)
    aa2 = divmod(eSecond - aa1[0] * 3600, 60)
    aa3 = eSecond - aa1[0] * 3600 - aa2[0] * 60
    return str(aa1[0]) + " h " + str(aa2[0]) + " m " + str(aa3) + " s"


def time2Second(strtime):
    aa1 = strtime.replace(" ", "")
    aa2 = aa1.replace("h", "_").replace('m', '_').replace('s', '').split('_')
    return int(aa2[0])*3600 + int(aa2[1])*60 + int(aa2[2])
